package org.hxzon.tapestry5.validator;

import org.apache.tapestry5.Field;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.ValidationException;
import org.apache.tapestry5.ioc.MessageFormatter;
import org.apache.tapestry5.services.FormSupport;
import org.apache.tapestry5.services.javascript.DataConstants;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;
import org.apache.tapestry5.validator.AbstractValidator;

public class RepeatSame extends AbstractValidator<String, String> {
    public RepeatSame(JavaScriptSupport javaScriptSupport) {
        super(String.class, String.class, "repeat-same", javaScriptSupport);
    }

    private String buildMessage(MessageFormatter formatter, Field field, String constraintValue) {
        return formatter.format(constraintValue, field.getLabel());
    }

    public void render(Field field, String constraintValue, MessageFormatter formatter, MarkupWriter writer, FormSupport formSupport) {
        if (formSupport.isClientValidationEnabled()) {
            javaScriptSupport.require("t5/core/validation");
            writer.attributes(DataConstants.VALIDATION_ATTRIBUTE, true, //
                    "data-validate-repeat-same", constraintValue.toString(), //
                    "data-repeat-same-message", buildMessage(formatter, field, constraintValue));
        }
    }

    public void validate(Field field, String constraintValue, MessageFormatter formatter, String value) throws ValidationException {
        //do nothing?
        //constraintValue is the target input id
    }
}
